package cn.congzhou.crm.utils;

import com.alibaba.fastjson.JSON;
import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

//这个注解表名把这个类交个Spring管理，给Controller做增强
@ControllerAdvice
public class ExceptionUtil implements TemplateExceptionHandler{

    private Logger logger = LoggerFactory.getLogger(ExceptionUtil.class);

//  异常处理器，当出现某个异常的时候调用此方法处理
    @ExceptionHandler(UnauthorizedException.class)
    public void handler(HttpServletResponse response, HandlerMethod method,
                        UnauthorizedException e) throws IOException {
//      method.getMethod()获取的是当前访问的没有权限的方法
//      判断没有权限的方法上是否贴有@ResponseBody注解
        if(method.getMethod().isAnnotationPresent(ResponseBody.class)){
            response.setContentType("text/json;charset=UTF-8");
            ResultJSON result = new ResultJSON();
            result.mark("对不起，您没有权限执行该操作");
            response.getWriter().print(JSON.toJSONString(result));
        }else{
            throw e;
        }
    }

    //处理所有异常
    /*@ExceptionHandler(Exception.class)
    public void handlerException(HttpServletResponse response,Throwable e) throws IOException {
        e.printStackTrace();
        //TODO 还没想好怎么处理先跳走吧
        response.sendRedirect("/employee/list.do");
    }*/

    /**
     * freemarker 模板异常处理方法,防止页面崩溃
     * @param te
     * @param env
     * @param out
     * @throws TemplateException
     */
    @Override
    public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
        try {
            te.printStackTrace();
            logger.error("解析freeMark出错",te);
            out.write("【解析出错了】");
        } catch (IOException e) {
            logger.error("IO流出错",e);
        }
    }
}
